<template>
  <div>
    <vab-card>
      <template #header>
        <span class="leve_title">折扣赠品策略查询</span>
      </template>
      <template #default>
        <el-form
          :ref="(el: any) => (searchFormRef = el)"
          :model="searchForm"
          label-width="80px"
          class="form_search composite_form"
        >
          <el-row :gutter="24">
            <el-col
              v-for="(item, i) in GiveIndexSearch" :key="i" v-bind="colLay"
            >
              <!-- 默认项 -->
              <el-form-item
                v-if="item.type == 'select'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabSelectForm
                  :multiple="item.multiple"
                  :options="selectOptions(item.prop)"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>

              <el-form-item
                v-if="item.type == 'lazySelect'"
                :label="item.label"
                :prop="item.prop"
              >
                <!-- <CreditLazySelect
                  :type="item.lazyType"
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                /> -->
              </el-form-item>

              <!-- input -->
              <el-form-item
                v-if="item.type == 'input'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabInputForm
                  v-model.trim="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
              <!-- time -->
              <el-form-item
                v-if="item.type == 'time'"
                :label="item.label"
                :prop="item.prop"
              >
                <VabTimeForm
                  v-model="searchForm[item.prop]"
                  @keyup.enter.native="onkeydown"
                />
              </el-form-item>
            </el-col>
            <!-- 按钮 -->
            <el-col v-bind="btnLay">
              <div class="flex_just_end">
                <VabButton title="查询" type="primary" @click="handleSearch()" />
                <VabButton title="重置" @click="resetForm(searchFormRef)" />
              </div>
            </el-col>
          </el-row>
        </el-form>
      </template>
    </vab-card>
    <!-- 主 -->
    <vab-card shadow="always">
      <template #header>
        <div class="flex_sb">
          <span class="leve2_title">折扣赠品策略明细</span>
          <div class="flex_just_end">
            <VabButton update title="审核撤回" @click="handleClick('revoke')" />
            <VabButton update title="变更" @click="handleClick('update')" />
            <VabButton update title="复制" @click="handleClick('copy')" />
            <VabButton title="停用" @click="handleClick('stop')" />
            <VabButton title="新建" type="primary" @click="handleClick('create')" />
          </div>
        </div>
      </template>
      <el-table
        border
        height="460"
        style="width: 100%"
        :data="data.dataSource"
        v-loading="data.loading"
      >
        <el-table-column align="center" label="序号" width="60" fixed="left">
          <template #default="{ row, $index }">
            <label
              class="el-checkbox"
              :class="{ 'is-checked': radioKey == $index }"
              @click="handleCurrentChange($index)"
            >
              <span
                class="el-checkbox__input"
                :class="{ 'is-checked': radioKey == $index }"
              >
                <span class="el-checkbox__inner"></span>
              </span>
              <span style="margin-left: 4px;">{{ (data.pageNum - 1) * data.pageSize + ($index + 1) }}</span>
            </label>
          </template>
        </el-table-column>
        <el-table-column
          v-for="(item, i) in data.cloums"
          :key="i"
          :width="item.width"
          :min-width="100"
          :prop="item.prop"
          :label="item.label"
          :align="item.type == 'money' || item.type == 'number' ? 'right' : 'center'
            "
        >
          <template #default="{ row }">
            <!-- 自定义 -->
            <div v-if="item.type == 'custom'">
              <span
                v-if="item.prop == 'number'"
                class="ellipsis link"
                @click="handleOperate('toDetail', row)"
              >
                {{ row[item.prop] || '--' }}
              </span>
              <span v-if="item.prop == 'status'">
                <el-tag
                  class="ml-2"
                  :type="ReturnnStatus(row.status, 'type')"
                >
                  {{ ReturnnStatus(row.status, 'label') }}
                </el-tag>
              </span>
              <span class="ellipsis" v-if="item.prop == 'effective_date'">
               {{ `${row.effective_start} / ${row.effective_end}` }}
              </span>
              <span class="ellipsis" v-if="item.prop == 'level'">
               {{ `${row.level}级` }}
              </span>
              <span class="ellipsis" v-if="item.prop == 'type'">
                <el-tag class="ml-2" > {{ '指定产品满数量赠' }} </el-tag>
              </span>
            </div>
            <!-- 正常 -->
            <div v-else class="ellipsis">
              {{ _FieldFormat(row[item.prop], item.type) }}
            </div>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" align="center" width="120" fixed="right">
          <template #default="scope">
            <VabButton v-if="isShowToHandle(scope.row.status)" title="去处理" type="primary" @click="handleOperate('toHandle', scope.row)" />
            <VabButton v-if="isShowToDetail(scope.row.status)" title="查看详情" type="primary" @click="handleOperate('toDetail', scope.row)" />
          </template>
        </el-table-column>
      </el-table>
      <div class="flex_just_end">
        <el-pagination
          background
          small="small"
          v-model:current-page="data.pageNum"
          v-model:page-size="data.pageSize"
          layout="total, prev, pager, next,sizes, jumper"
          :page-sizes="[20, 50, 100, 200]"
          :pager-count="10"
          :total="data.count"
          @current-change="handlePageNum"
          @size-change="handlePageSize"
        />
      </div>
      <VabButton update title="下载" @click="_onExportBasicExcel"/>
    </vab-card>
  </div>
</template>
<!-- 草稿箱 -->
<script lang="ts" setup>
defineOptions({
  name: 'GiveawayIndex',
})
/**
 * @import
 */
import {
  GiveIndexSearch,
  GiveIndexCloums,
  ReturnSelectOptions,
  ReturnnStatus,
} from './component/tools'
import {
  DateFormat,
  FieldFormat,
  StrShift,
} from '~/src/utils/utils'
import { FormInstance } from 'element-plus'
import { orderDiscountBatch, orderDiscountList, orderDiscountOptions } from '~/src/api/dms/order';
import { onExportBasicExcel } from '~/src/utils/excelJs';

/**
 * @var
 */
const colLay = {
  xs: 24, sm: 12, md: 12, lg: 6, xl: 6,
}
const btnLay = {
  xs: 24, sm: 24, md: 24, lg: 12, xl: 12,
}
const proxy: any = getCurrentInstance()?.proxy
const router = useRouter()
const searchFormRef = ref<any>(null)
const searchForm = reactive<any>({})
const data = reactive<any>({
  dataSource: [],
  cloums: [],
  pageNum: 1,
  pageSize: 20,
  count: 0,
  search: {},
})
data.dataSource = []
data.cloums = GiveIndexCloums

let isCheck = ref(false)
const currentRow = ref<any>(null) //选中块
const radioKey = ref<any>(-1) //唯一值

/**
 * @method
 */
const handleSearch = async (value = '') => {
  isCheck.value = true
  await _GetProductList()
  proxy.$Message('查询成功', 'success')
}
// 重置
const resetForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  isCheck.value = false

  data.pageNum = 1
  data.pageSize = 20
  await formEl.resetFields()
  await _GetProductList()
  proxy.$Message('重置成功', 'success')
}
// 回车
const onkeydown = (value: any) => {
  isCheck.value = true
  _GetProductList()
}
// 单选
const handleCurrentChange = (i: number) => {
  if (i == radioKey.value) {
    radioKey.value = -1
    currentRow.value = null
    return
  }
  radioKey.value = i
  currentRow.value = data.dataSource[i]
}
// 页码
const handlePageNum = (value: any) => {
  data.pageNum = value
  radioKey.value = -1
  currentRow.value = null
  _GetProductList()
}
// 页数
const handlePageSize = (value: any) => {
  data.pageSize = value
  _GetProductList()
}
// 下载
const _onExportBasicExcel = async () => {

  if (!data.dataSource.length) {
    proxy.$Message('导出数据为空，请进行筛选查询后再进行导出！', 'warning')
    return
  }

  const cloums = await GiveIndexCloums.map((item: any) => {
    return {
      title: item.label,
      dataIndex: item.prop,
      width: item.width,
    }
  })
  data.pageSize = data.count

  await _GetProductList(false)

  const fileName = '折扣赠品策略明细'

  const list = data.dataSource.map((item: any) => {
    return {
      ...item,
      effective_date: `${item.effective_start} / ${item.effective_end}`,
      // level: `${item.level}级`,
      status: ReturnnStatus(item.status, 'label'),
      type: '指定产品满数量赠'
    }
  })
  await onExportBasicExcel(cloums, list, fileName, fileName)
  proxy.$Message('下载成功！', 'success')
  data.pageSize = 20
}
// 点击事件
const handleClick = (value: any, row = {}) => {
  const _row: any = row

  if (value == 'create') {
    router.push({
      path: '/customer/giveawayCreate',
      query: {
        from: 'create',
      }
    })
    return
  }

  if (!currentRow.value) {
    proxy.$Message('请选择需要操作的折扣赠品策略明细！', 'warning')
    return
  }

  const { uid, status } = currentRow.value

  if (value == 'toCustomDetail') {
    router.push('/credit/customDetail?id=' + uid)
    return
  }

  if (value == 'copy') {
    router.push({
      path: '/customer/giveawayCreate',
      query: {
        from: 'copy',
        id: uid,
        status: -1
      }
    })
    return
  }
  if (value == 'update') {
    if (status != 2) {
      proxy.$Message('该策略不可被操作！', 'warning')
      return
    }
    router.push({
      path: '/customer/giveawayCreate',
      query: {
        from: 'update',
        id: uid,
        status
      }
    })
    return
  }

  if (value == 'revoke' || value == 'stop') {
    if (value == 'revoke' && status != 1) {
      proxy.$Message('该策略不可被操作！', 'warning')
      return
    }
    if (value == 'stop' && status != 2) {
      proxy.$Message('该策略不可被操作！', 'warning')
      return
    }

    orderDiscountBatch({ uid, action: value }).then(res => {
      proxy.$Message(`${value == 'revoke' ? '撤回' : '停用'}成功！`, 'success')
      refresh()
    })
    return
  }
}
// 操作事件
const handleOperate = (type: string, { uid, status }: any) => {
  if (type == 'toHandle') {
    router.push({
      path: '/customer/giveawayCreate',
      query: {
        from: 'toHandle',
        id: uid,
        status
      }
    })
  }
  if (type == 'toDetail') {
    router.push({
      path: '/customer/giveawayDetail',
      query: {
        id: uid,
      }
    })
  }
}

//刷新
const refresh = () => {
  radioKey.value = -1
  currentRow.value = null
  _GetProductList()
}

// 字段级格式化
const _FieldFormat = (value: string, type = '') => {
  if (type == 'time') return DateFormat(value, 'YYYY-MM-DD')
  return FieldFormat(value, type)
}
// 筛选项
const _GetProductSearch = async () => {
  try {
    const optionRes = await orderDiscountOptions()
    const { create_user_name, customer, name, number, use_org } = optionRes.data

    data.search = {
      create_user_name,
      customer,
      use_org: use_org.map((item: any) => {
        return {
          use_org_id: item.use_org_id || '',
          use_org_name: item.use_org_name || '--'
        }
      }),
      number: number.map((item: any) => {
        return {
          number: item.number,
          number_str: item.number || '--'
        }
      }),
      name,
    }

  } catch (error) { }
}
// 筛选项返回值
const selectOptions = (value: string) => {
  if (!data.search) return
  if (!value) return
  return ReturnSelectOptions(data.search, value)
}
// 获取数据
const _GetProductList = async (lay = true) => {
  if (lay) data.loading = true

  let _searchForm = { ...searchForm }
  if (!isCheck.value) _searchForm = {}

  const { effective_date } = _searchForm

  const query = {
    page: data.pageNum,
    pagesize: data.pageSize,
    uid: _searchForm.uid ? StrShift(_searchForm.uid) : '',
    name: _searchForm.name ? StrShift(_searchForm.name) : '',
    number: _searchForm.number ? StrShift(_searchForm.number) : '',
    type: _searchForm.type ? StrShift(_searchForm.type) : '',
    status: _searchForm.status ? StrShift(_searchForm.status) : '',
    use_org_id: _searchForm.use_org_id ? StrShift(_searchForm.use_org_id) : '',
    customer_uid: _searchForm.customer_uid ? StrShift(_searchForm.customer_uid) : '',
    create_user_name: _searchForm.create_user_name ? StrShift(_searchForm.create_user_name) : '',
    effective_start: effective_date ? DateFormat(effective_date[0]) : '',
    effective_end: effective_date ? DateFormat(effective_date[1]) : '',
  }

  try {
    const res = await orderDiscountList({ ...query })
    data.dataSource = res.data.list
    data.count = res.data.count
    data.loading = false
  } catch (error) { }
}

/**
 * @实例
 */
const isShowToHandle = (status: string | number) => {
  const _status = `${status}`
  if (_status == '0') return true
  return false
}
const isShowToDetail = (status: string | number) => {
  const _status = `${status}`
  if (_status != '0') return true
  return false
}

onActivated(async () => {
  await _GetProductSearch()
  refresh()
})
</script>
